package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.tree.DefaultMutableTreeNode;

import model.MP3FileList;

import view.GUI;

/**
 * The ButtonActionListener provides the save and discard functions.
 * 
 *
 */
public class ButtonActionListener implements ActionListener {

	private GUI mainGUI;
	
	public ButtonActionListener(GUI gui) {
		this.mainGUI = gui;
	}

	@Override
	public void actionPerformed(ActionEvent e) {		
		if (e.getActionCommand().equals("Speichern")) {
			//check if there is a mp3node selected
			if(this.mainGUI.getCurrentMP3Node() != null){					
				//change the attributes of guis current mp3 node
				this.mainGUI.getCurrentMP3Node().changeTitleOfMP3File(this.mainGUI.getTitle());
				this.mainGUI.getCurrentMP3Node().changeAlbumOfMP3File(this.mainGUI.getAlbum());
				this.mainGUI.getCurrentMP3Node().changeArtistOfMP3File(this.mainGUI.getArtist());
				
				//only save the year if it is a number
				String newYear = this.mainGUI.getYear();
				if(newYear != null && newYear.matches("[0-9]+"))
					this.mainGUI.getCurrentMP3Node().changeYearOfMP3File(Integer.parseInt(newYear));

				this.mainGUI.getCurrentMP3Node().changeCoverofMP3File(this.mainGUI.getImagePane());
				try {
					ID3Writer.writeMP3ToFile(this.mainGUI.getCurrentMP3Node().getMP3File());
					
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				
				DefaultMutableTreeNode parent = (DefaultMutableTreeNode) this.mainGUI.getCurrentMP3Node().getParent();
				MP3FileList list = (MP3FileList) parent.getUserObject();
				
			}
		}
		else if (e.getActionCommand().equals("Verwerfen")) {
			// redraw with current MP3-Node 
			this.mainGUI.redrawGUIWithCurrentMP3Node();
		}
	}
}
